package com.zerdoor.service.impl;

import com.zerdoor.dao.LoginDao;
import com.zerdoor.model.UserInfo;
import com.zerdoor.service.LoginService;
import com.zerdoor.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaobo on 2014/9/4.
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginDao loginDao;

    @Override
    public boolean verifyLogin(UserInfo tuser,Map<String,String> loginMap,HttpServletRequest request) {
        String password = loginMap.get("password");
        if(tuser!=null){
            if(password!=null && !"".equals(password)
                    && tuser.getPsd().equals(MD5.getMd5String(password))){

                //权限方式session
                List<Map<String,Object>> perms = loginDao.getPermsByRoleId(tuser.getRoleId());
                if(perms.size() > 0){
                    List<String> list = new ArrayList<String>();
                    for(Map<String,Object> temp : perms){
                        if(temp.get("perm")!=null && !"".equals(temp.get("perm").toString())){
                            String perm = temp.get("perm").toString().replaceAll("\\*","");
                            String[] permArr = perm.split(",");
                            for(String str : permArr){
                                if(!list.contains(str)){
                                    list.add(str);
                                }
                            }

                        }
                    }
                    tuser.setPerms(list);
                }
                //存入会话
                request.getSession().setAttribute("curManager",tuser);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    @Override
    public UserInfo getTuserByName(String name) {
        return loginDao.getTuserByName(name);
    }


}
